package com.hayden.fileMonitor.util;

import com.hayden.fileMonitor.pojo.TcpInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class WindowsTools {
        public static List<TcpInfo> TcpInfoParser() throws IOException {
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "netstat -ano|findstr \"21\"");
            Process p = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            int count = 0;
            List<TcpInfo> tcpInfos = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                count++;
                if(0<count && count<5){continue;}
                String[] parts = line.trim().split("\\s+");
                if (parts.length == 5) {
                    String protocol = parts[0];
                    String localAddress = parts[1];
                    String foreignAddress = parts[2];
                    String state = parts[3];
                    Integer pid = Integer.parseInt(parts[4]);
                    TcpInfo tcpInfo = new TcpInfo(protocol, localAddress, foreignAddress, state, pid);
                    tcpInfos.add(tcpInfo);
                }
            }
            return tcpInfos;
        }

        public static String CheckConnection(List<TcpInfo> tcpInfos){
            for (TcpInfo tcp:
                 tcpInfos) {
                String localAddress = tcp.getLocalAddress();
                if (localAddress.contains(":3389")) {
                    String connectionIP = tcp.getForeignAddress();
                    return connectionIP;
                }
            }
            return null;
        }

}
